package com.kqb.sgpicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.kqb.sgpicturebackend.common.ErrorCode;
import com.kqb.sgpicturebackend.exception.BusinessException;
import com.kqb.sgpicturebackend.utils.ThrowUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

/**
 * @author 杉果树皮
 * @date 2025/5/6 17:37
 * @description: 图片url上传
 */
@Service
public class PictureUploadByUrl extends PictureUploadTemplate {
    @Override
    public String getOriginalFilename(Object inputSource) {
        String fileUrl = (String) inputSource;
        return FileUtil.mainName(fileUrl);
    }

    @Override
    public void processFile(Object inputSource, File tempFile) {
        String fileUrl = (String) inputSource;
        HttpUtil.downloadFile(fileUrl, tempFile);
    }

    @Override
    public void validatePicture(Object inputSource) {
        String fileUrl = (String) inputSource;
        ThrowUtils.throwNotIf(StrUtil.isBlank(fileUrl), new BusinessException(ErrorCode.PARAMS_ERROR, "图片路径为空"));
        // 1. 验证url格式
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件格式错误");
        }
        // 2. 校验url协议
        ThrowUtils.throwNotIf(!fileUrl.startsWith("http://") && !fileUrl.startsWith("https://"), new BusinessException(ErrorCode.PARAMS_ERROR, "文件协议错误"));
        // 3. 发送head请求验证文件是否存在
        try (HttpResponse response = HttpUtil.createRequest(Method.HEAD, fileUrl).execute()) {
            if (response.getStatus() != HttpStatus.HTTP_OK) {
                return;
            }
            // 4. 校验文件类型
            List<String> fileType = Arrays.asList("images/jpg", "images/jpeg", "images/png", "images/webp");
            String contentType = response.header("Content-Type");
            ThrowUtils.throwIf(!fileType.contains(contentType), new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误"));
            // 5. 校验文件大小
            String contentLengthStr = response.header("Content-Length");
            try {
                long contentLength = Long.parseLong(contentLengthStr);
                //文件大小
                final long maxSize = 1024 * 1024;
                ThrowUtils.throwIf(!(contentLength > maxSize * 2), new BusinessException(ErrorCode.PARAMS_ERROR, "上传文件大小不能超过2MB"));
            } catch (NumberFormatException e) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "类型转换错误");
            }
        }
    }
}
